function [error, stddev] = cv_dt(depth, Xcv, Ycv, Xtest, Ytest)
% cross-validation error.
%
% Usage:
%
%   error = cv_dt(depth, Xcv, Ycv, Xtest, Ytest)
%
% This function outputs an 'error' corresponding to the
% value in 'DEPTH'. X is the examples from the training set. Y is the 
% label of the training examples.
%
% SEE ALSO
%   MAKE_CV_PARTITION

n = size(Xcv, 1);
n_folds = 8;

%choose the number of partitions
part = make_cv_partition(n, n_folds);

% error vector 
err = zeros(n_folds, 2); 

for i = 1:n_folds
    
    fprintf('Currently training on fold #%d ... \n', i); 
    
    %find the indicies of partitiion i
    train_ind = find(part~=i);
    test_ind = find(part==i);
    
    %Index the X and Y arrays by the appropriate indicies
    train_points = Xcv(train_ind,:); %Training set i (all indicies ~= i)
    train_labels = Ycv(train_ind,:); %Training labels i (all indicies ~= i)
    ith_points = Xcv(test_ind,:); %Test set i (all indicies == i)
    ith_labels_true = Ycv(test_ind); % Test labels i (all indices == i)
       
    %TRAIN
    train_struct = dt_train_multi(train_points, train_labels, depth);
    ith_labels = dt_test_multi(train_struct, ith_points);
    test_labels = dt_test_multi(train_struct, Xtest); 
    
    %Compare the predictions by the algorithm to the acual values. This is done by
    %comparing the signs of test_labels and test_labels_true element-wise.
    %The error will be the number of misclassifications over the total number
    %of test points.
    
    %Call rank_err function
    err(i,1) = rank_err(ith_labels, ith_labels_true);
    err(i,2) = rank_err(test_labels, Ytest); 
end

error = mean(err);
stddev = std(err); 

